package models

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

func NewTableRecord(dbName, tableName string, data map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, dbName)
	values, sql := InsertSql(tableName, data)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

func NewOrUpdateRecord(dbName, tableName string, data map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, dbName)
	values, sql := InsertOrUpdateSql(tableName, data)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

func UpdateTableRecord(dbName, tableName string, data map[string]interface{}, id interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, dbName)
	condition := fmt.Sprintf(`%v = %v`, primaryKeyByTableName(tableName), id)
	values, sql := UpdateSql(tableName, data, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

func DeleteTableRecord(dbName, tableName string, id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, dbName)
	condition := fmt.Sprintf(`%v = %v`, primaryKeyByTableName(tableName), id)
	sql := DeleteSql(tableName, condition)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

func primaryKeyByTableName(TableName string) string {
	switch TableName {
	case TableClientUser:
		return "uid"
	case TableClientPassport:
		return "uid"
	default:
		return "id"
	}
}
